package cn.stylefeng.guns.modular.demos.util;

import java.security.MessageDigest;

import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;

import okhttp3.OkHttpClient;
import okhttp3.Request;

public class SHAUtil {
    private static final String CA_OFFICIAL_WECHAT_TICKET = "CA_OFFICIAL_WECHAT_TICKET";
    private static OkHttpClient okHttpClient = new OkHttpClient();
    
    /**
     * @return
     * @Comment SHA256实现
     * @Author Ron
     * @Date 2017年9月13日 下午3:30:36
     */
    public static String sha256Encode(String inStr) throws Exception {
        MessageDigest sha = null;
        sha = MessageDigest.getInstance("SHA-256");

        byte[] byteArray = inStr.getBytes("UTF-8");
        byte[] md5Bytes = sha.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
    
    
    /**
     * @Comment SHA1实现
     * @Author Ron
     * @Date 2017年9月13日 下午3:30:36
     * @return
     */
    public static String shaEncode(String inStr) throws Exception {
        MessageDigest sha = null;
        try {
           // sha = MessageDigest.getInstance("SHA");
        	sha = java.security.MessageDigest.getInstance("SHA-1");  
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
 
        byte[] byteArray = inStr.getBytes("UTF-8");
        byte[] md5Bytes = sha.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
    
    public static String getWxH5Ticket(String accessToken) throws Exception {
        //String wxTicket = cacheComponent.getRaw(CA_OFFICIAL_WECHAT_TICKET);
        //if (StringUtils.isEmpty(wxTicket)) {
            //尝试获取微信公众号Ticket
            String ticketJson = okHttpClient.newCall(
                    new Request.Builder()
                            .url("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi")
                            .get()
                            .build()).execute().body().string();
            JSONObject jsonObject = JSONObject.parseObject(ticketJson);
            String wxTicket = jsonObject.getString("ticket");
            if (!StringUtils.isEmpty(wxTicket)) {
                Integer expires_in = jsonObject.getInteger("expires_in");
                //在过期前重置
                Integer cacheExpireSec = expires_in * 4 / 5;
                //cacheComponent.putRaw(CA_OFFICIAL_WECHAT_TICKET, wxTicket, cacheExpireSec);
            } else {
                throw new RuntimeException("回复错误:" + ticketJson);
            }
       // }
        return wxTicket;
    }

//jsapi_ticket=kgt8ON7yVITDhtdwci0qee8raUqYv1sG6QwGp8mBiwHlcuYaqTY6iFXfB23bgUM-LeXwU55pRk-aiWwFj6HTpg&noncestr=4673da2829cf41ab92dc1bdcbf3b260b&timestamp=1598780036&url=http://jj.kman.gov.cn/zdcl-wx/mh5/index.html?code=081DCg0w3iZiRU2EI70w3OpmYc1DCg0C&state=123
//jsapi_ticket=kgt8ON7yVITDhtdwci0qee8raUqYv1sG6QwGp8mBiwHlcuYaqTY6iFXfB23bgUM-LeXwU55pRk-aiWwFj6HTpg&noncestr=4673da2829cf41ab92dc1bdcbf3b260b&timestamp=1598780036460&url=http://jj.kman.gov.cn/zdcl-wx/mh5/index.html?code=081DCg0w3iZiRU2EI70w3OpmYc1DCg0C&state=123    
    
    public static void main(String args[]) throws Exception {
        String str = new String("jsapi_ticket=kgt8ON7yVITDhtdwci0qee8raUqYv1sG6QwGp8mBiwHlcuYaqTY6iFXfB23bgUM-LeXwU55pRk-aiWwFj6HTpg&noncestr=e1a3f3a4ed454ce083c1b9464bc0de1d&timestamp=1598782370&url=http://jj.kman.gov.cn/zdcl-wx/mh5/index.html?code=001BlpFa1B1Vwz0EtuIa1mLvAK0BlpFP&state=123");
        System.out.println("原始：" + str);
        System.out.println("SHA后：" + shaEncode(str));
    }

}
